package com.cfets.annualAssessment.securityConfig;

import com.cfets.annualAssessment.entity.Account;
import com.cfets.annualAssessment.entity.Role;
import com.cfets.annualAssessment.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by woniper on 15. 3. 6..
 */
@Service
public class WebSecurityUserDetailsService implements UserDetailsService {

    @Autowired
    private AccountService accountService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String accountName) throws UsernameNotFoundException {
//        passwordEncoder.encode("111111");
        Account account = accountService.getAccountByUserName(accountName);
        //status不是启用3，用户不存在
        if(account == null||account.getStatus()!=3)
            throw new UsernameNotFoundException(accountName);


        List<GrantedAuthority> authorities = buildUserAuthority(account.getRoleIds());

        return buildUserForAuthentication(account, authorities);
    }

    private User buildUserForAuthentication(Account user,
                                            List<GrantedAuthority> authorities) {

        return new User(user.getUsername(), user.getPassword(),
                true, true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(String roleIds) {

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(0);
        for (String item : roleIds.split(",")) {
            authorities.add(new SimpleGrantedAuthority(item.trim()));
        }

        return authorities;
    }


}
